//
//  MLHomeViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/20.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "MLHomeViewController.h"
#import "SwitchView.h"
#import <UIImage+GIF.h>


#import "InitDataViewController.h"
#import "ThirdpartyPhoneViewController.h"

@interface MLHomeViewController ()<UIScrollViewDelegate,SwitchViewDelegate>
@property (nonatomic,strong) UIScrollView *scrollView;
@property NSInteger currentIndex;
@property float bgViewHeight;
@property SwitchView *switchView;
//专属恋人的红点
@property (strong, nonatomic)UIView *recommendNewLabel;

@property (nonatomic, strong) NSMutableArray *userArr;
@property (nonatomic,assign)BOOL left;
@end

@implementation MLHomeViewController

- (void)buttonAction:(id)buttonAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//状态栏颜色
    
    

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([[EaseMob sharedInstance].chatManager isLoggedIn]&&![[EaseMob sharedInstance].chatManager isConnected]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
        }
    });
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        MLUser *user = [MLUser currentUser];
        if (user&&user.isUserInited) {
            if ((user.notifyPhoneNum == nil&&user.mobilePhoneNumber == nil)||(user.mobilePhoneNumber&&user.mobilePhoneNumber.length == 0)||(user.mobilePhoneNumber == nil&&user.notifyPhoneNum.length == 0)) {
                ThirdpartyPhoneViewController *thirdPVC = [[ThirdpartyPhoneViewController alloc] init];
                thirdPVC.noRegister = YES;
                [Utils pushTabbarHidden:thirdPVC Selfvc:self];
            }else{
                
                if (user.notifyPhoneNum == nil||user.notifyPhoneNum.length==0) {
                    user.notifyPhoneNum = user.mobilePhoneNumber;
                    [user saveInBackground];
                }
            }
        }
    });
    
   
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  
    
    self.left = YES;
    self.title = @"口袋";
    
    if (![Utils cheackConfigurationScreen]) {
        [self rightItemTitle:@"全部"];
        
    }
    
    self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    // 加载喜欢的内容
    self.userArr = [[NSMutableArray alloc]init];
    
    
   

    //视图高度
    self.bgViewHeight = DeviceHeight;
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    

    CGFloat width = 100;
    if (IS_IPHONE_6){
        width = 100;
    }else if (IS_IPHONE_6_PLUS){
        width = 120;
    }else{
        width = 80;
    }
    
    self.switchView = [[SwitchView alloc] initWithFrame:CGRectMake( 0, 0, DeviceWidth - width*2, titleHeight)];
    _switchView.delegate = self;
    _switchView.TitleArr = @[@"空闲恋人", @"梦想恋人"];
    [_switchView initview];
//    [view addSubview:self.switchView];
    self.navigationItem.titleView = _switchView;
    

    
    //初始化滑动视图
    [self initScroll];
    //初始化VC
    [self initViewController];
    
    //新专属恋人
    self.recommendNewLabel = [[UIView alloc]initWithFrame:CGRectMake((DeviceWidth/2)+90, (titleHeight-7.5)/2, 7.5, 7.5)];
    self.recommendNewLabel.layer.masksToBounds = YES;//开启圆角
    [self.recommendNewLabel.layer setCornerRadius:7.5/2];
    self.recommendNewLabel.backgroundColor = UIColorFromRGB(0xFE6A66);
    [self.switchView addSubview:self.recommendNewLabel];
     self.recommendNewLabel.alpha = 0;
 
    
    [ShareData shareData].homeVC = self;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recommendPush) name:@"recommendPush" object:nil];
    
   
    
}
//收到推送发通知出现编辑推荐红点
- (void)recommendPush
{
     [Utils Hidden:self.recommendNewLabel Bool:YES];
}



-(void)cmd:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    EMMessage *message = [dic objectForKey:@"message"];
    if (message.messageBodies&&message.messageBodies.count) {
        EMCommandMessageBody *body= message.messageBodies.lastObject;
        if(body.action &&[body.action isEqualToString:ACTION_NEW_RECOMMENT]){
             [Utils Hidden:self.recommendNewLabel Bool:YES];
        }
    }
}


- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cmd" object:nil];
}

#pragma mark - init

-(void)initScroll
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, self.bgViewHeight)];
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.scrollsToTop = NO;
    [self.view addSubview:self.scrollView];
    
    [self.scrollView setContentSize:CGSizeMake(DeviceWidth * (2), DeviceHeight)];
    //    [self.scrollView setContentOffset:CGPointMake(0*DeviceWidth, 0)animated:YES];
    
    
}

-(void)initViewController
{
    self.find = [[OonlineViewController alloc]init];
    self.find.view.frame = CGRectMake(0, 0, DeviceWidth, self.bgViewHeight);
    [self.scrollView addSubview:self.find.view];
    [self addChildViewController:self.find];
    
    self.recommend = [[RecommendViewController alloc]init];
    self.recommend.view.frame = CGRectMake(DeviceWidth, 0, DeviceWidth, self.bgViewHeight);
    [self.scrollView addSubview:self.recommend.view];
    [self addChildViewController:self.recommend];
    
    
    __weak __typeof(self) weakSelf = self;
    self.switchView.ButtonActionBlock = ^(NSInteger buttonTag){
        
        weakSelf.currentIndex = buttonTag-100;
        
        POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPScrollViewContentOffset];
        positionAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(DeviceWidth* (weakSelf.currentIndex-1),0)];
        positionAnimation.springBounciness = 8.f;
        [weakSelf.scrollView pop_addAnimation:positionAnimation forKey:@"layerPositionAni2mation"];
        
        
        if (weakSelf.currentIndex == 1) {
            //改变右边item 筛选
            if (![Utils cheackConfigurationScreen]) {
                [weakSelf rightItemTitle:@"全部"];
                
            }
            
            [weakSelf clickButtonIsLeft:YES];
//            if (weakSelf.recommendNewLabel.alpha == 0) {
//                [Utils Hidden:weakSelf.recommendNewLabel Bool:YES];
//            }
        }else if (weakSelf.currentIndex == 2){
            [weakSelf clickButtonIsLeft:NO];
            [weakSelf.find cellresetContainerView];
            weakSelf.navigationItem.rightBarButtonItem = nil;
            //改变右边item 定制恋人
//            [weakSelf.recommend xsimge];
//            [weakSelf rightItemTitle:@"home_editor's-choice_the-custom-lover_icon"];
            if (weakSelf.recommendNewLabel.alpha != 0) {
                [Utils Hidden:weakSelf.recommendNewLabel Bool:NO];
                if (weakSelf.recommend!=nil) {
                    [weakSelf.recommend loadArticleData];
                }
            }
            
        }

    };
    
    self.currentIndex = 1;
}



#pragma  mark SwitchViewDelegate
- (void)clickButtonIsLeft:(BOOL)left
{
    self.left = left;
    
}
//右上角初始化
-(void)rightItemTitle:(NSString*)title
{
    //    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(rightItem:)];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:title]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightItem:)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

//右上角item触发方法
- (void)rightItem:(UIBarButtonItem*)sender
{
    if (self.left) {
        [self.find filterUser];
    }else{
        if (![Utils userinit:self]) {
            return;
        }
    }
}

//通知滑动了页面
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pagewidth = self.scrollView.frame.size.width;
    int currentPage = floor((self.scrollView.contentOffset.x - pagewidth/ (2)) / pagewidth) + 1;
    self.currentIndex = currentPage+1;
    [self.switchView swipeAction:(100+currentPage+1)];
}


//滑动条滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.scrollView.contentOffset.x != 0) {
        [self.switchView sliding:self.scrollView.contentOffset.x];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
